package com.genius.dingding.util;



import java.net.URLDecoder;
import java.security.MessageDigest;
import java.util.Formatter;

import javax.servlet.http.HttpServletRequest;


import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.request.OapiGetJsapiTicketRequest;
import com.dingtalk.api.request.OapiServiceGetCorpTokenRequest;
import com.dingtalk.api.response.OapiGetJsapiTicketResponse;
import com.dingtalk.api.response.OapiServiceGetCorpTokenResponse;
import com.dingtalk.oapi.lib.aes.DingTalkEncryptException;
/**
 * 获取企业工作的token
 * @author Administrator
 *
 */
public class GetDingDing {
	private static GetDingDing getPrimaryId = null;
	
	private static String ticket=null;
	private static String token=null;
	
	public static GetDingDing getInstance(){
		 if (getPrimaryId == null) {  
	            synchronized (GetDingDing.class) {  
	                if (getPrimaryId == null) {
	                	System.out.println("新建GetDingDing");
	                	getPrimaryId = new GetDingDing();  
	                }  
	            }  
	        }
		return getPrimaryId;  
	}
	
	private GetDingDing(){
        try {
        	setToken();
        	setJsapiTicket();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public synchronized  void setToken(){
		try {
//			DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/service/get_corp_token");
//			OapiServiceGetCorpTokenRequest request = new OapiServiceGetCorpTokenRequest();
//			request.setAuthCorpid(GeniusConfig.CORPID);
//			OapiServiceGetCorpTokenResponse response = client.execute(request,GeniusConfig.CUSTOMKEY,GeniusConfig.CUSTOMSECRECT, "abcdefg");
//			String errcode = response.getErrorCode();
//        	if(errcode==null || !errcode.equals("0")){
//        		throw new Exception(response.getErrmsg());
//        	}else{
//        		token = response.getAccessToken();
//        	}
			//直接取已经使用过的
        	token = HttpHelper.httpGetString(GeniusConfig.QIYEGONGZUO+"/dingding/gettoken.do");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			token = null;
			e.printStackTrace();
		}
	}
	
	
	public String getToken(){
		if(token == null){
			setToken();
		}
		token = HttpHelper.httpGetString(GeniusConfig.QIYEGONGZUO+"/dingding/gettoken.do");
		return token;
		
	}
	public String getTicket(){
		ticket = HttpHelper.httpGetString(GeniusConfig.QIYEGONGZUO+"/dingding/getjsapi.do");
		return ticket;
		
	}
	 /**
     * 获取JSTicket, 用于js的签名计算
     * 正常的情况下，jsapi_ticket的有效期为7200秒，所以开发者需要在某个地方设计一个定时器，定期去更新jsapi_ticket
     */
	public void setJsapiTicket(){
        try {
//        	DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/get_jsapi_ticket");
//        	OapiGetJsapiTicketRequest req = new OapiGetJsapiTicketRequest();
//        	req.setTopHttpMethod("GET");
//        	OapiGetJsapiTicketResponse response = client.execute(req, getToken());
//        	String errcode = response.getErrorCode();
//        	if(errcode==null || !errcode.equals("0")){
//        		throw new Exception(response.getErrmsg());
//        	}else{
//        		ticket = response.getTicket();
//        	}
        	ticket = HttpHelper.httpGetString(GeniusConfig.QIYEGONGZUO+"/dingding/getjsapi.do");
        } catch (Exception e) {
        	ticket = null;
        	e.printStackTrace();
        }
//        System.out.println("jsTicket----"+jsTicket);
    }
	public  String sign(String nonceStr, long timeStamp, String url) throws DingTalkEncryptException{
		String jsticket = getTicket();
		String plainTex = "jsapi_ticket=" + jsticket +"&noncestr=" + nonceStr +"&timestamp=" + timeStamp + "&url=" + url;
        String signature = "";
        try{
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(plainTex.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
            return signature;
        }catch (Exception e){
            throw new DingTalkEncryptException(DingTalkEncryptException.COMPUTE_SIGNATURE_ERROR);
        }finally{
        	jsticket = null;
        }
    }
	private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash){
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }
	/**
     * 计算当前请求的jsapi的签名数据<br/>
     * <p>
     * 如果签名数据是通过ajax异步请求的话，签名计算中的url必须是给用户展示页面的url
     *
     * @param request
     * @return
     */
    @SuppressWarnings("deprecation")
	public  JSONObject getConfig(HttpServletRequest request) {
    	JSONObject object = new JSONObject();
        String urlString = request.getRequestURL().toString();
        String queryString = request.getQueryString();

        String queryStringEncode = null;
        String url;
        if (queryString != null) {
            queryStringEncode = URLDecoder.decode(queryString);
            url = urlString + "?" + queryStringEncode;
        } else {
            url = urlString;
        }
        String nonceStr = "abcdefg";
        long timeStamp = System.currentTimeMillis() / 1000;
        String signedUrl = url;
        String signature = null;
        String agentid = GeniusConfig.AGENTID;
        //134935688
        
        try {

            signature = sign(nonceStr, timeStamp, signedUrl);

        } catch (DingTalkEncryptException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        object.put("jsticket", getTicket());
        object.put("signature", signature);
        object.put("nonceStr", nonceStr);
        object.put("timeStamp", timeStamp);
        object.put("corpId", GeniusConfig.CORPID);
        object.put("agentid", agentid);
        object.put("token", getToken());
        object.put("url", url);
//        String configValue = "{jsticket:'" + ticket + "',signature:'" + signature + "',nonceStr:'" + nonceStr + "',timeStamp:'"
//                + timeStamp + "',corpId:'" + CORP_ID + "',agentid:'" + agentid + "'}";
//        System.out.println("getConfig----"+configValue);
        return object;
    }
    public  JSONObject getConfig(String url) {
    	System.out.println(url+"----------------------");
//    	JSONObject object = new JSONObject();

//        String nonceStr = "abcdefg";
//        long timeStamp = System.currentTimeMillis() / 1000;
//        String signedUrl = url;
//        String signature = null;
//        String agentid = GeniusConfig.AGENTID;
//
//        try {
//
//            signature = sign( nonceStr, timeStamp, signedUrl);
//
//        }  catch (DingTalkEncryptException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//        object.put("jsticket", getTicket());
//        object.put("signature", signature);
//        object.put("nonceStr", nonceStr);
//        object.put("timeStamp", timeStamp);
//        object.put("corpId", GeniusConfig.CORPID);
//        object.put("agentid", agentid);
//        object.put("token", getToken());
//        object.put("url", url);
    	JSONObject object = JSONObject.parseObject(HttpHelper.httpGetString(GeniusConfig.QIYEGONGZUO+"/dingding/getconfig.do?pageUrl="+url));
    	System.out.println(GeniusConfig.QIYEGONGZUO+"/dingding/getconfig.do?pageUrl="+url);
        return object;
    }
}